package com.edais.actions;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.edais.domain.*;
import com.edais.log.IpLog;
import com.edais.service.*;
import com.edais.util.*;
import com.edais.util.weixinAbout.WeixinRquestUtil;
import com.lb.sssq.service.DepositService;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wxuser")

public class WeiXinUserAction implements Serializable {

    private static final long serialVersionUID = -7278557094943445497L;
    private static final Log logger = LogFactory.getLog(WeiXinUserAction.class);

    @Autowired
    private UserService userService;

    @Autowired
    private UserCardService userCardService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private WeixinBindingService weixinBindingService;
    @Autowired
    private RateRisesCouponsService rateRisesCouponsService;
    @Autowired
    private DepositService depositService;

    @Autowired
    private ChannelWelfareParametersService channelWelfareParametersService;

    @Autowired
    private ErrorMessageService errorMessageService;

    @Autowired
    private KcodeChannelService kcodeChannelService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private PointService pointService;

    @Autowired
    private SystemSettingService systemSettingService;

    /**
     * 修改交易密码
     */
    @RequestMapping(value = "/updatePassword")
    public void updatePassword(HttpServletRequest request, HttpServletResponse response) {
        String logInfo = "";
        try {
            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);
            logger.info("header：" + header.toString());

            Long userId = header.getUserId();
            if (userId == null) {
                ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
                return;
            }
            User user = this.userService.getUserDetail(userId.toString());
            if (user == null) {
                ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.BUSINESSE_ERROR);
                ResponseUtil.write(response, result);
                return;
            }
            // 先判断用户是否存在(目前只针对手机用户)
            if (StringUtils.isBlank(user.getMobile())) {
                logger.info("用户userId=" + userId + "调用修改交易密码修改：用户手机号为null");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
                ResponseUtil.write(response, checkDto);
                return;
            }
            logInfo = "用户mobile=" + user.getMobile() + "userId=" + userId + "调用修改交易密码";
            // 解密请求参数
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);
            logger.info(logInfo + "data：" + paramsMap.toString());
            String password = paramsMap.getString("password");//新密码
            String passwordOld = paramsMap.getString("passwordOld");


            if (StringUtils.isBlank(password)) {
                logger.info(logInfo + "修改交易密码：新密码为空");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NULL);
                ResponseUtil.write(response, checkDto);
                return;
            }
            // 新密码为6-20位数字或大小写字母
            boolean flag = false;
            flag = password.matches("[a-zA-Z0-9]{6,20}");
            if (!flag) {
                logger.info(logInfo + "交易密码重置：密码不规范");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);
                ResponseUtil.write(response, checkDto);
                return;
            }

            String passwordMd5 = MD5.md5(password);
            String passwordOldMd5 = MD5.md5(passwordOld);

            if (!passwordOldMd5.equals(user.getPassword_cash())) {
                logger.info(logInfo + "修改交易密码修改：老的交易密码错误");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.PASSWORDCASH_OLD_ERROR);
                ResponseUtil.write(response, checkDto);
                return;
            }


            String type = "mobile";
            this.userService.resetPswCash(user.getMobile(), passwordMd5, type);
            ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
            ResponseUtil.write(response, result);
            return;

        } catch (Exception e) {
            logger.error(logInfo + "修改交易密码修改：异常:", e);
            ResponseUtil.write(response, new ResultDTO<>(ResultCode.FAILED,
                    Message.CnDescriptionExpression.BUSINESSE_ERROR));
            return;
        }
    }

    /**
     * 用户交易密码验证
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/checkPasswordCash")
    public void checkPasswordCash(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String logInfo = "";
        logger.info("进入javaservice checkPasswordCash方法：");
        try {
            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);
            logger.info("header：" + header.toString());

            Long userId = header.getUserId();
            if (userId == null) {
                ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
                return;
            }
            User user = this.userService.getUserDetail(userId.toString());
            if (user == null) {
                logger.info(logInfo + "用户不存在");
                ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS,
                        Message.CnDescriptionExpression.BUSINESSE_ERROR);
                ResponseUtil.write(response, result);
                return;
            }
            logInfo = "用户mobile=" + user.getMobile() + "验证交易密码";
            // 解密请求参数
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);
            logger.info("data：" + paramsMap.toString());

            String passwordCash = paramsMap.getString("passwordCash");
            String passwordMd5 = MD5.md5(passwordCash);

            if (passwordMd5.equals(user.getPassword_cash())) {
                logger.info(logInfo + "验证成功");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
                ResponseUtil.write(response, checkDto);
                return;
            }
            logger.info(logInfo + "验证失败，原密码错误");
            ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                    Message.CnDescriptionExpression.PASSWORDCASH_OLD_ERROR);
            ResponseUtil.write(response, checkDto);
            return;

        } catch (Exception e) {
            e.printStackTrace();

            logger.error(logInfo + "用户交易密码验证：异常:", e);
            ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            ResponseUtil.write(response, result);
            return;
        }

    }

    /**
     * 更新邀请码
     *
     * @throws Exception
     */
    @RequestMapping(value = "/updateInvitationCode")
    public void updateInvitationCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String logInfo = "";
        try {
            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);
            logger.info("header：" + header.toString());
            // 用户ID
            Long userId = header.getUserId();
            if (userId <= 0) {
                ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
                return;
            }
            User user = this.userService.getUserDetail(userId.toString());
            if (user == null) {
                ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS,
                        Message.CnDescriptionExpression.BUSINESSE_ERROR);
                ResponseUtil.write(response, result);
                return;
            }

            logInfo = "用户mobile" + user.getMobile() + "调用更新邀请码接口";
            // 解密请求参数
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);

            // 邀请码
            String invitationCode = paramsMap.getString("invitationCode");// 邀请码

            if (StringUtils.isBlank(invitationCode)) {
                logger.info(logInfo + "invitationCode为空");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        "邀请码不能为空!");
                ResponseUtil.write(response, checkDto);
                return;
            }
            if (!invitationCode.matches(Consts.PHONECHECK)) {
                logger.info(logInfo + "手机号非法");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        "请输入规范的手机号码!");
                ResponseUtil.write(response, checkDto);
                return;
            }
            // 获取邀请人信息
            Map<String, Object> map = new HashMap<>();
            map.put("mobile", invitationCode);
            User userOther = userService.getUserByParm(map);

            if (userOther != null) {
                if (invitationCode.equals(user.getMobile())) {
                    ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                            "邀请码不能是自己的手机号！");
                    ResponseUtil.write(response, checkDto);
                    return;
                }
                // 邀请人注册时间必须比被邀请人早
                if (userOther.getReg_time().getTime() > user.getReg_time().getTime()) {
                    ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                            "邀请人的注册时间必须早于您的注册时间！");
                    ResponseUtil.write(response, checkDto);
                    return;
                }
            } else {
                logger.info(logInfo + "您输入的邀请人不存在！");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        "您输入的邀请码不存在！");
                ResponseUtil.write(response, checkDto);
                return;
            }


            userService.updateInvitationCode(invitationCode, userId.toString());

            ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS,
                    Consts.SUCCESS_DESCRIBE);
            ResponseUtil.write(response, result);
            return;
        } catch (Exception e) {
            logger.error(logInfo + "更新邀请码异常！", e);
            ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS,
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            ResponseUtil.write(response, result);
            return;
        }
    }

    /**
     * 根据手机号查找用户信息
     *
     * @throws Exception
     */
    @RequestMapping(value = "/findWeixinUserByPhoneNum")
    public void findWeixinUserByPhoneNum(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入findWeixinUserByPhoneNum方法：");
        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }

        Map<String, Object> params = RequestUtil.decodeData(request);
        logger.info("data：" + params.toString());

        // 手机号
        String phoneNum = String.valueOf(params.get("phoneNum"));
        logger.info("=========传过来的phoneNum：" + phoneNum);
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phoneNum);
        User user = userService.getUserByParm(map);
        // 密码掩饰处理
        if (user != null) {
            if (user.getPassword() != null && user.getPassword().length() > 0) {
                user.setPassword("default");
            }
            if (user.getPassword_cash() != null && user.getPassword_cash().length() > 0) {
                user.setPassword_cash("default");
            }
        }

        ResultDTO<User> result = new ResultDTO<>(ResultCode.SUCCESS);
        result.setRecord(user);
        logger.info("=========获取的user信息：" + result);
        ResponseUtil.write(response, result);
        logger.info("=========findWeixinUserByPhoneNum方法结束");
    }

    /**
     * 登陆
     *
     * @param request
     * @return response
     * @throws Exception
     */
    @RequestMapping(value = "/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }

        JSONObject params = RequestUtil.decodeDataJson(request);
        logger.info("data：" + params.toString());

        String userName = params.getString("userName");// 用户名
        String setupFlag = params.getString("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的

        String loginFlag = params.getString("loginFlag");// 验证码，密码登录标识

        String ip = RequestUtil.getClientIP(request);

        IpLogBean logBean = new IpLogBean();
        logBean.setIp(ip);
        logBean.setAction("登录");
        logBean.setStatus(Consts.ERROR_CN);
        if ("2".equals(setupFlag)) {
            logBean.setDetail(userName + "在APP端进行了登录操作");
        } else {
            logBean.setDetail(userName + "在WEB端进行了登录操作");
        }

        if (null != loginFlag && !"".equalsIgnoreCase(loginFlag) && "1".equalsIgnoreCase(loginFlag)) {
            try {
                ResultDTO checkResult = loginPasswordCheck(params);
                if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                    ResponseUtil.write(response, checkResult);
                    return;
                }
                // 登陆主处理
                ResultDTO result = userService.dealLoginPassWord(params);

                if (StringUtils.isNotBlank(params.getString("userId"))) {
                    logBean.setStatus(Consts.SUCCESS_CN);
                    logBean.setUser(params.getString("userId"));
                    IpLog.printIpLog(logBean);
                }
                ResponseUtil.write(response, result);
            } catch (Exception e) {
                logger.error("登陆异常:" + e.getMessage());
                Map<String, Object> errorMap = errorMessageService.getErrorMessage("BUSINESSE_ERROR");
                String errMsg = getErrorMsg(errorMap);
                ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED, errMsg));
            }
        } else {
            try {
                ResultDTO checkResult = loginCheck(params);
                if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                    ResponseUtil.write(response, checkResult);
                    return;
                }

                // 登陆主处理
                ResultDTO result = userService.dealLogin(params);

                if (StringUtils.isNotBlank(params.getString("userId"))) {
                    logBean.setStatus(Consts.SUCCESS_CN);
                    logBean.setUser(params.getString("userId"));
                    IpLog.printIpLog(logBean);
                }

                ResponseUtil.write(response, result);
            } catch (Exception e) {
                logger.error("登陆异常:" + e.getMessage());
                Map<String, Object> errorMap = errorMessageService.getErrorMessage("BUSINESSE_ERROR");
                String errMsg = getErrorMsg(errorMap);
                ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED, errMsg));
            }
        }

    }

    /**
     * 注册
     *
     * @param request
     * @return response
     * @throws Exception
     */
    @RequestMapping(value = "/register")
    public void register(HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }

        // 解密请求参数
        JSONObject params = RequestUtil.decodeDataJson(request);
        logger.info("data：" + params);

        String userName = params.getString("userName");// 用户名-手机号
        String passwordCash = params.getString("passwordCash");// 密码
        String channel = params.getString("channel");// 渠道
        // 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String setupFlag = params.getString("setupFlag");
        String invitationCode = params.getString("invitationCode");// 邀请码
        // 微信ID
        String weixinId = params.getString("weixinId");

        String ip = CommonUtil.getClientIP(request);

        IpLogBean logBean = new IpLogBean();
        logBean.setIp(ip);
        logBean.setAction("注册");
        logBean.setStatus(Consts.ERROR_CN);
        if ("2".equals(setupFlag)) {
            logBean.setDetail(userName + "在APP端进行了注册操作");
        } else {
            logBean.setDetail(userName + "在WEB端进行了注册操作");
        }

        try {
            ResultDTO checkResult = registerCheck(params);
            if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                ResponseUtil.write(response, checkResult);
                return;
            }
            // 验证码失效

            if (StringUtils.isBlank(channel)) {
                params.put("channel", "OTHERS");
                channel = "OTHERS";
            }

            // 创建用户
            User user = new User();
            String passwordMd5 = "";
            if (StringUtils.isNotBlank(passwordCash)) {
                passwordMd5 = MD5.md5(passwordCash);
            }
            user.setMobile(userName);
            user.setPassword_cash(passwordMd5);
            user.setChannel(channel);
            user.setLastest_login_ip(ip);
            String token = "register" + "_" + CommonUtil.getUuid();
            user.setLogin_token(token);
            if ("2".equals(setupFlag)) {
                user.setUtm_source_type("MOBILE");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
            } else {
                user.setUtm_source_type("CHANNEL");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
            }

            // 注册邀请码
            if (StringUtils.isNotBlank(invitationCode)) {
                user.setInviterInvitationCode(invitationCode.toUpperCase());
            }
            user.setWeixin_id(weixinId == null ? "" : weixinId);

            // 添加用户(T_TUSER表和USER_INFO表)
            this.userService.addUsers(user);

            // 注册成功
            Map<String, Object> jsonMap = new HashMap<>();
            jsonMap.put("userId", user.getId());
            jsonMap.put("userName", userName);
            jsonMap.put("identityName", "");
            jsonMap.put("idCard", "");
            jsonMap.put("ftpPathOriginal", "");
            jsonMap.put("ftpPathDispose", "");
            jsonMap.put("emailValidate", user.getEmail_validate());
            jsonMap.put("idcardValidate", "N");
            jsonMap.put("mobileValidate", user.getMobile_validate());
            jsonMap.put("email", "");
            jsonMap.put("mobile", user.getMobile());
            jsonMap.put("bankCardValidate", "N");
            jsonMap.put("weixinId", user.getWeixin_id());

            // uuid生成-2.1.0版本新增
            jsonMap.put("uuid", user.getLogin_token());

            logBean.setStatus(Consts.SUCCESS_CN);
            if (StringUtils.isNotBlank(ip)) {
                logBean.setUser(user.getId() + "");
                IpLog.printIpLog(logBean);
            }

            // 按渠道统一发放福利
            try {
                Map<String, Object> welfareParams = new HashMap<>();
                welfareParams.put("userId", user.getId());
                welfareParams.put("channelId", user.getUtm_source());
                welfareParams.put("mobile", user.getMobile());
                welfareParams.put("channelEnName", channel);
                channelWelfareParametersService.addWelfareBychannelEnName(welfareParams, request);
            } catch (Exception e) {
                logger.error("注册赠送福利异常:" + e.getMessage());
            }

            // 注册送积分
            if (null != user.getId() && !StringUtil.isEmpty(user.getMobile())) {
                logger.info("#### 开始执行--->注册送积分 #####");
                pointService.registerPoint(user);
                logger.info("#### 执行完成--->注册送积分 #####");
            } else {
                logger.info("#### 注册送积分时，用户信息有误，userId=" + user.getId() + ",mobile=" + user.getMobile() + " ####");
            }

            // 处理返回结果
            ResultDTO result = new ResultDTO(ResultCode.SUCCESS);
            result.setRecord(jsonMap);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            logger.error("注册异常:" + e.getMessage());
            ResponseUtil.write(response, ResultConstant.FAILED);
        }
    }

    /**
     * 交易密码重置
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/resetPassword")
    public void resetPassword(HttpServletRequest request, HttpServletResponse response) {
        String logInfo = "";
        try {

            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);
            logger.info("header：" + header.toString());

            Long userId = header.getUserId();
            if (userId == null) {
                ResponseUtil.write(response, ResultConstant.NOT_LOGIN);
                return;
            }
            User user = this.userService.getUserDetail(userId.toString());
            if (user == null) {
                ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS,
                        Message.CnDescriptionExpression.BUSINESSE_ERROR);
                ResponseUtil.write(response, result);
                return;
            }

            String mobile = user.getMobile();
            logInfo = "用户mobile=" + mobile + "调用交易密码重置";
            // 解密请求参数
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);
            logger.info(logInfo + "data：" + paramsMap.toString());

            String passwordCash = paramsMap.getString("passwordCash");

            if (StringUtils.isBlank(mobile)) {
                logger.info(logInfo + "交易密码重置：手机号为空");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.BUSINESSE_ERROR);
                ResponseUtil.write(response, checkDto);
                return;
            }

            if (StringUtils.isBlank(passwordCash)) {
                logger.info(logInfo + "交易密码重置：新密码为空");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NULL);
                ResponseUtil.write(response, checkDto);
                return;
            }

            // 非法手机号检查
            boolean flag = mobile.matches(Consts.PHONECHECK);
            if (!flag) {
                logger.info(logInfo + "交易密码重置：手机号格式不对");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
                ResponseUtil.write(response, checkDto);
                return;
            }

            // 新密码为6-20位数字或大小写字母
            flag = passwordCash.matches("[a-zA-Z0-9]{6,20}");
            if (!flag) {
                logger.info(logInfo + "交易密码重置：密码不规范");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);
                ResponseUtil.write(response, checkDto);
                return;
            }

            String passwordMd5 = MD5.md5(passwordCash);
            // 先判断用户是否存在(目前只针对手机用户)
            int count = userService.phoneIsExisted(mobile);
            if (count <= 0) {
                logger.info(logInfo + "交易密码重置：手机号未注册");
                ResultDTO<String> checkDto = new ResultDTO<>(ResultCode.FAILED,
                        Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
                ResponseUtil.write(response, checkDto);
                return;
            }

            String type = "mobile";
            this.userService.resetPswCash(mobile, passwordMd5, type);

            ResultDTO<String> result = new ResultDTO<>(ResultCode.SUCCESS, Consts.SUCCESS_DESCRIBE);
            ResponseUtil.write(response, result);
            return;
        } catch (Exception e) {
            logger.error(logInfo + "交易密码重置：异常:", e);
            ResultDTO<String> result = new ResultDTO<>(ResultCode.FAILED,
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            ResponseUtil.write(response, result);
            return;
        }
    }

    /**
     * 根据邀请码查看邀请人信息
     */
    @RequestMapping(value = "/getUserInfoByICd")
    public void getUserInfoByICd(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> jsonMap = new HashMap<>();
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        String invitationCode = paramsMap.get("invitationCd");// 邀请码

        if (StringUtils.isBlank(invitationCode)) {
            jsonMap.put("inviterInfo", "");
            String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            // 处理返回结果
            CommonUtil.responseJson(result, response);
            result = CommonUtil.setResultStringCn(jsonMap, Consts.CHECK_CODE, Consts.SUCCESS_DESCRIBE, "");
        }

        try {
            // 根据邀请码获取邀请人信息
            User user = userService.getInviterInfo(invitationCode.toUpperCase());
            String inviterInfo = "";

            if (user != null) {
                String mobile = user.getMobile();
                if (StringUtils.isBlank(mobile)) {
                    String email = user.getEmail();
                    // 邮箱中间*号处理
                    inviterInfo = StrUtil.hiddenEmailContent(email);
                } else {
                    // 手机中间4位*号处理
                    inviterInfo = StrUtil.hiddenMobileContent(mobile);
                }
            }
            jsonMap.put("inviterInfo", inviterInfo);
            String result = CommonUtil.setResultStringCn(jsonMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            // 处理返回结果
            CommonUtil.responseJson(result, response);
            return;
        } catch (Exception ex) {
            logger.debug("user/getUserInfoByICd 异常" + ex.getMessage());
            String result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.ERROR_CODE,
                    Consts.ErrorMsg.MSG00001, Message.CnDescriptionExpression.BUSINESSE_ERROR);
            // 处理返回结果
            CommonUtil.responseJson(result, response);
        }
    }

    /**
     * 获取验证码
     *
     * @param request
     * @return response
     * @throws Exception
     */
    @RequestMapping(value = "/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }
        RequestHeader header = RequestUtil.decodeHeader(request);
        logger.info("header：" + header.toString());
        try {
            // 解密请求参数
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);

            // 数据检查
            ResultDTO<String> checkDto = getCaptchaCheck(paramsMap);
            if (null == checkDto || checkDto.codeEq(ResultCode.FAILED)) {
                ResponseUtil.write(response, checkDto);
                return;
            }

            // 业务处理
            paramsMap.put("userMobile", checkDto.getRecord());
            // 查询短信发送每日限额次数
            String infoTime = this.userService.getSystemSettingValue("day_captcha_time");
            if (null == infoTime || "".equalsIgnoreCase(infoTime)) {
                infoTime = "5";
            }
            // 查询是否限制短信发送
            ResultDTO result = userService.getCaptcha(paramsMap, infoTime);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            logger.error("获取验证码发生异常:", e);
            ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.FAILED);
            String result = resultDTO.toJsonString();
            logger.info("result：" + result);
            ResponseUtil.write(response, result);
        }
    }

    /**
     * 验证码检验
     *
     * @param request
     * @return response
     * @throws Exception
     * @throws IllegalArgumentException
     * @throws Exception
     */
    @RequestMapping(value = "/checkCaptcha")
    public void checkCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }

        JSONObject params = RequestUtil.decodeDataJson(request);

        try {
            // 数据检查
            ResultDTO checkResult = checkCaptchaCheck(params);
            if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                // 处理返回结果
                ResponseUtil.write(response, checkResult);
                return;
            }

            logger.debug("请求手机号：" + params.getString("phoneNum") + "请求验证码：" + params.getString("checkCode") + "发送标识:"
                    + params.getString("setupFlag"));

            // 业务处理
            ResultDTO result = userService.checkCaptcha(params);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("GET_CAPTCHA_FAILED");
            String errMsg = getErrorMsg(errorMap);
            logger.error("获取验证码发生异常:", e);
            ResponseUtil.write(response, new ResultDTO(ResultCode.SUCCESS, errMsg));
        }
    }

    /**
     * 判断手机号是否被使用
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/phoneIsExisted")
    public void phoneIsExisted(HttpServletRequest request, HttpServletResponse response) {
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        // String phoneNum = paramsMap.get("phoneNum");
        try {
            // 数据检查
            Map<String, String> checkMap = getCheckNum(paramsMap);
            if (0 != checkMap.size() && !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
                String result = CommonUtil.setResultStringCn(new HashMap<>(), checkMap.get("code"), "",
                        checkMap.get("message"));
                // 处理返回结果
                CommonUtil.responseJson(result, response);
                return;
            }
            /*
             * Map<String, String> resMap = new HashMap<String,String>();
			 * resMap.put("rescode", Consts.SUCCESS_CODE);
			 * resMap.put("resmsg_cn",
			 * Message.CnDescriptionExpression.USER_CAN_USE);
			 */
            String result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE, "",
                    Message.CnDescriptionExpression.USER_CAN_USE);
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            logger.error("检验用户发生异常:" + e.getMessage());
            String result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.ERROR_CODE, "",
                    Message.CnDescriptionExpression.USER_IS_EXISTED);
            CommonUtil.responseJson(result, response);
        }
    }

    public Map<String, String> getCheckNum(Map<String, String> paramsMap) throws Exception {
        Map<String, String> resMap = new HashMap<String, String>();
        String mobileNum = paramsMap.get("phoneNum");

        // 手机号合法检查
        boolean flagMobile = mobileNum.matches(Consts.PHONECHECK);
        if (!flagMobile) {
            logger.error("发送格式数据检查失败：手机号非法");
            resMap.put("code", Consts.CHECK_CODE);
            resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
            return resMap;
        }
        // 判断手机号是否被使用
        int count = userService.phoneIsExisted(mobileNum);
        // if("REGISTER".equals(type) || "BINDING_MOBILE".equals(type)){
        // 注册及其绑定手机号
        if (count > 0) {
            logger.error("发送格式数据检查失败：注册或者绑定手机号时手机号被使用");
            resMap.put("code", Consts.CHECK_CODE);
            resMap.put("message", Message.CnDescriptionExpression.MOBILE_IS_BOUND);
            return resMap;
        }

        // resMap.put("code", Consts.SUCCESS_CODE);
        // resMap.put("message", Consts.SUCCESS_DESCRIBE);
        // }
        return resMap;
    }

    /**
     * 获取验证码数据检查
     *
     * @param paramsMap
     * @return
     * @throws Exception
     */
    private ResultDTO<String> getCaptchaCheck(JSONObject paramsMap) throws Exception {

        // 手机号
        String mobileNum = paramsMap.getString("phoneNum");
        /*
		 * 验证码类别： 注册验证码(REGISTER), 登录验证码(WXLOGIN), 重置登陆密码(FORGET_PASSWORD),
		 * 解绑手机(MODIFY_MOBILE), 绑定手机(BINDING_MOBILE), MODIFY_PASSWORD:修改登陆密码
		 * CASHDRAW:提现, RESETPASSWORD :修改登录密码/重置登陆密码
		 * 
		 */
        String type = paramsMap.getString("type");
        // 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String setupFlag = paramsMap.getString("setupFlag");
        // 用户id
        String userId = paramsMap.getString("userId");

        String userMobile = "";

        // 验证码类别
        if (StringUtils.isBlank(type)) {
            logger.error("发送验证码数据检查失败：验证码类别为空");
            return ResultConstant.FAILED;
        }

        // 发送标识
        if (!StrUtil.setupFlagCheck(setupFlag)) {
            logger.error("发送验证码数据检查失败：发送标识无效！发送标识:" + setupFlag);
            return ResultConstant.FAILED;
        }

        // 验证码类别
        if ("MODIFY_MOBILE".equals(type) || "MODIFY_PASSWORD".equals(type) || "CASHDRAW".equals(type)) {
            // 用户id
            if (StringUtils.isBlank(userId)) {
                logger.error("发送验证码数据检查失败：用户id为空");
                return ResultConstant.FAILED;
            }
            // 查询用户的手机号
            userMobile = captchaService.getMobileById(userId);
        } else if ("REGISTER".equals(type) || "FORGET_PASSWORD".equals(type) || "BINDING_MOBILE".equals(type)
                || "RESETPASSWORD".equals(type)) {
            // 手机号
            if (StringUtils.isBlank(mobileNum)) {
                logger.error("发送验证码数据检查失败：手机号为空");
                return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_IS_NULL);
            }
            // 手机号合法检查
            boolean flagMobile = mobileNum.matches(Consts.PHONECHECK);
            if (!flagMobile) {
                logger.error("发送验证码数据检查失败：手机号非法");
                return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
            }
            // 判断手机号是否被使用
            int count = userService.phoneIsExisted(mobileNum);
            if ("REGISTER".equals(type) || "BINDING_MOBILE".equals(type)) {
                // 注册及其绑定手机号
                if (count > 0) {
                    logger.error("发送验证码数据检查失败：注册或者绑定手机号时手机号被使用");

                    return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_IS_BOUND);
                }
            } else {
                // 重置密码
                if (count <= 0) {
                    logger.error("发送验证码数据检查失败：重置密码时手机号无注册");
                    return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
                }
            }
            userMobile = mobileNum;
        } else if ("WXLOGIN".equals(type)) {
            // 手机号
            if (StringUtils.isBlank(mobileNum)) {
                logger.error("发送验证码数据检查失败：手机号为空");
                return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_IS_NULL);
            }
            // 手机号合法检查
            boolean flagMobile = mobileNum.matches(Consts.PHONECHECK);
            if (!flagMobile) {
                logger.error("发送验证码数据检查失败：手机号非法");
                return new ResultDTO<>(ResultCode.FAILED, Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
            }
            userMobile = mobileNum;
        } else {
            logger.error("发送验证码数据检查失败：验证码类别无效！验证码类别：" + type);
            return new ResultDTO<>(ResultCode.FAILED);
        }
        ResultDTO<String> dto = new ResultDTO<>(ResultCode.SUCCESS);
        dto.setRecord(userMobile);
        return dto;
    }

    /**
     * 校验验证码数据检查
     *
     * @param params
     * @return
     * @throws Exception
     */
    private ResultDTO checkCaptchaCheck(JSONObject params) throws Exception {

        String phoneNum = params.getString("phoneNum");
        String checkCode = params.getString("checkCode");
        // 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String setupFlag = params.getString("setupFlag");

        // 手机号码
        if (StringUtils.isBlank(phoneNum)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("MOBILE_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 验证码
        if (StringUtils.isBlank(checkCode)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("CAPTCHA_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 发送标识
        if (!StrUtil.setupFlagCheck(setupFlag)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000016");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }
        return ResultConstant.SUCCESS;
    }

    /**
     * 注册数据检查
     *
     * @param params
     * @return
     * @throws Exception
     */
    private ResultDTO registerCheck(JSONObject params) throws Exception {

        String userName = params.getString("userName");// 用户名-手机号
        String passwordCash = params.getString("passwordCash");// 密码
        String channel = params.getString("channel");// 渠道
        String setupFlag = params.getString("setupFlag");
        String invitationCode = params.getString("invitationCd");// 邀请码
        String checkCode = params.getString("checkCode");// 验证码

        String regType = params.getString("regType");
        // 校验用户名不能为空
        if (StringUtils.isBlank(userName)) {
            logger.error("注册数据检查失败： 用户名为空");
            return new ResultDTO(ResultCode.FAILED,
                    Message.CnDescriptionExpression.USER_IS_NULL);
        }

        // 校验密码不能为空
        if (!"web".equals(regType)) {
            if (StringUtils.isBlank(passwordCash)) {
                logger.error("注册数据检查失败： 密码为空");
                return new ResultDTO(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NULL);
            }

            // 密码为6-20位数字或大小写字母
            boolean flagPassword = passwordCash.matches("[a-zA-Z0-9]{6,20}");
            if (!flagPassword) {
                logger.error("注册数据检查失败：  密码不规范");
                return new ResultDTO(ResultCode.FAILED,
                        Message.CnDescriptionExpression.PASSWORD_IS_NON_STANDARD);
            }
        }

        // 验证码
        if (StringUtils.isBlank(checkCode)) {
            logger.error("注册数据检查失败：验证码为空");
            return new ResultDTO(ResultCode.FAILED,
                    Message.CnDescriptionExpression.CAPTCHA_IS_NULL);
        }

        // 发送标识
        if (!StrUtil.setupFlagCheck(setupFlag)) {
            logger.error("注册数据检查失败： 发送标识无效！发送标识:" + setupFlag);
            return new ResultDTO(ResultCode.FAILED);
        }

        // 非法手机号检查
        boolean flag = userName.matches(Consts.PHONECHECK);
        if (!flag) {
            logger.error("注册数据检查失败：  手机号格式不对");
            return new ResultDTO(ResultCode.FAILED,
                    Message.CnDescriptionExpression.MOBILE_IS_NON_STANDARD);
        }

        // 先判断用户是否存在(目前只针对手机用户)
        int count = userService.phoneIsExisted(userName);
        if (count > 0) {
            logger.error("注册数据检查失败：  手机号已注册");
            return new ResultDTO(ResultCode.FAILED,
                    Message.CnDescriptionExpression.USER_IS_EXISTED);
        }

        // 邀请码检查,如果填写了邀请码，就必须是非本人且存在的邀请码
        if (StringUtils.isNotBlank(invitationCode)) {
            // 判读输入的邀请码是否合法（非本人且存在的）
            int codeCount = userService.getInviteCodeCount(invitationCode.toUpperCase());
            if (codeCount == 0) {
                logger.error("注册数据检查失败：  输入邀请码不存在！");
                return new ResultDTO(ResultCode.FAILED,
                        Message.CnDescriptionExpression.INVITATIONCD_IS_WRONG);
            }
        }

        // 验证码检查
        userService.checkCaptcha(params);
        // 验证码验证码检查失败
		/*
		 * if(StringUtils.isBlank(map.get("dealFlag")) ||
		 * !Consts.SUCCESS_CODE.equals(map.get("dealFlag"))){
		 * logger.error("注册数据检查失败： 验证码检验失败！"); resMap.put("code",
		 * Consts.CHECK_CODE); resMap.put("message",
		 * Message.CnDescriptionExpression.CHECK_CAPTCHA_FAILED); return resMap;
		 * }
		 */
        return ResultConstant.SUCCESS;
    }

    /**
     * 登陆数据检查
     *
     * @param params
     * @return
     * @throws Exception
     */
    private ResultDTO loginCheck(JSONObject params) throws Exception {
        String userName = params.getString("userName");// 用户名
        String type = params.getString("type");// 登陆类型：手机或者邮箱
        String setupFlag = params.getString("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String checkCode = params.getString("checkCode");// 验证码

        if (StringUtils.isBlank(userName)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("USER_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 验证码
        if (StringUtils.isBlank(checkCode)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("CAPTCHA_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败：" + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        if (StringUtils.isBlank(type)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000015");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        if (!("mobile".equals(type) || "mail".equals(type))) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000015");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 发送标识
        if (!StrUtil.setupFlagCheck(setupFlag)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000016");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg + "！发送标识:" + setupFlag);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 验证码检查
        if (!("13774201428".equals(userName) && "811002".equals(checkCode))) {
            ResultDTO checkResult = userService.checkCaptcha(params);
            // 验证码验证码检查失败
            if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                Map<String, Object> errorMap = errorMessageService.getErrorMessage("CHECK_CAPTCHA_FAILED");
                String errMsg = getErrorMsg(errorMap);
                logger.error("登录数据检查失败：" + errMsg);
                return new ResultDTO(ResultCode.FAILED, errMsg);
            }

        }
        return ResultConstant.SUCCESS;
    }

    /**
     * 查询当前手机号是否已绑定
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryInfoMediaBinding")
    public void queryInfoMediaBinding(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice queryInfoMediaBinding方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String phoneNum = paramsMap.get("phoneNum");
        String mediaUid = paramsMap.get("mediaUid");

        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phoneNum);
        map.put("mediaUid", mediaUid);

        User user = userService.getUserByParm(map);

        WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
        mediaBinding.setMediaType("1");// 设置媒介类型（1、腾讯微信；2、腾讯微博；3、新浪微博）
        mediaBinding.setUserId(user.getId());// 用户Id
        mediaBinding.setInvitationCode("");// 邀请码暂时为空
        mediaBinding.setStatus("1");// 有效状态（0：无效；1：有效）
        mediaBinding.setCreatePer(String.valueOf(user.getId()));// 新用户
        mediaBinding.setMediaUid(mediaUid);
        mediaBinding.setCreateTime(new Date());

        try {
            int count = weixinBindingService.queryInfoMediaBinding(mediaBinding);
            if (count != 0) {
                logger.error("该手机已绑定微信！当前微信标识：" + mediaUid);
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                        Message.CnDescriptionExpression.WEIXIN_BINDING_INFO_ERROR);
            } else {
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                        Consts.SUCCESS_DESCRIBE, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CommonUtil.responseJson(result, response);

    }

    /**
     * 微信绑定平台用户
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/insertIntoMediaBinding")
    public void insertIntoMediaBinding(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice insertIntoMediaBinding方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String phoneNum = paramsMap.get("phoneNum");
        String mediaUid = paramsMap.get("mediaUid");

        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phoneNum);
        map.put("mediaUid", mediaUid);

        User user = userService.getUserByParm(map);

        WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
        mediaBinding.setMediaType("1");// 设置媒介类型（1、腾讯微信；2、腾讯微博；3、新浪微博）
        mediaBinding.setUserId(user.getId());// 用户Id
        mediaBinding.setInvitationCode("");// 邀请码暂时为空
        mediaBinding.setStatus("1");// 有效状态（0：无效；1：有效）
        mediaBinding.setCreatePer(String.valueOf(user.getId()));// 新用户
        mediaBinding.setMediaUid(mediaUid);
        mediaBinding.setCreateTime(new Date());

        try {
            weixinBindingService.insertIntoMediaBinding(mediaBinding);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("微信绑定失败！当前微信标识为：" + mediaUid);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.ADD_WEIXIN_BINDING_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 通过微信唯一标示查询用户ID
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getUseridByWeixinUid", method = RequestMethod.GET)
    public void getUseridByWeixinUid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getUseridByWeixinUid方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String mediaUid = paramsMap.get("mediaUid");

        Map<String, Object> map = new HashMap<>();
        map.put("mediaUid", mediaUid);

        try {
            Map<String, String> userInfomap = weixinBindingService.getUseridByWeixinUid(map);
            String userId = "";
            if (null != userInfomap) {
                userId = String.valueOf(userInfomap.get("ID"));
            } else {
                userId = "";
            }

            if (null == userId || "".equalsIgnoreCase(userId) || "null".equalsIgnoreCase(userId)) {
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                        Message.CnDescriptionExpression.USERID_BYWEIXIN_ERROR);
            } else {
                Map weixinMap = new HashMap<>();
                weixinMap.put("userId", userId);
                weixinMap.put("mobile", String.valueOf(userInfomap.get("MOBILE")));
                weixinMap.put("nickName", userInfomap.get("NICK_NAME"));
                result = CommonUtil.setResultStringCn(weixinMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[通过微信标识openid获取平台用户ID失败]微信标识meidaUid为：" + mediaUid + "&userId获取异常");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.USERID_BYWEIXIN_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 通过微信唯一标示查询用户ID
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
    public void getSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getSignature方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String mediaUid = paramsMap.get("mediaUid");

        Map<String, Object> map = new HashMap<>();
        map.put("mediaUid", mediaUid);

        try {
            Map<String, Object> signaTureMap = weixinBindingService.getSignature();
            if (null == signaTureMap) {
                signaTureMap = new HashMap<>();
            }
            result = CommonUtil.setResultStringCn(signaTureMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[获取signature签名]微信标识meidaUid为：" + mediaUid + "&SIGNATURE获取失败");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.SIGNATURE_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 添加全局token，signature签名数据
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/insertSignature")
    public void insertSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice insertSignature方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String ticket = paramsMap.get("ticket");
        String accessToken = paramsMap.get("accessToken");
        String createPer = paramsMap.get("createPer");

        // 设置参数
        Signature signTrue = new Signature();
        signTrue.setAccesstoken(accessToken);
        signTrue.setJsapid_Ticket(ticket);
        signTrue.setCreatePer(createPer);
        try {
            weixinBindingService.insertSignature(signTrue);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加全局TOKEN，signature签名失败！当前微信标识为：" + createPer);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.ADD_SIGNATURE_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 修改全局token，signature签名数据
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/updateSignature")
    public void updateSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice updateSignature方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String ticket = paramsMap.get("ticket");
        String accessToken = paramsMap.get("accessToken");
        String createPer = paramsMap.get("otXu5swhlifvm8B2u9DoGJc5yclo");

        logger.info(
                "****javasevice********ticket:" + ticket + "&accessToken:" + accessToken + "&createPer=" + createPer);

        try {
            weixinBindingService.updateSignature(paramsMap);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改全局TOKEN，signature签名失败！当前微信标识为：" + createPer);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.UPDATE_SIGNATURE_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 查询当前输入手机号，是否已绑定其他微信号
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getWeixinUidBindingByMobile", method = RequestMethod.GET)
    public void getWeixinUidBindingByMobile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getWeixinUidBindingByMobile方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String phoneNum = paramsMap.get("phoneNum");

        Map<String, Object> map = new HashMap<>();
        map.put("phoneNum", phoneNum);

        try {
            Map<String, String> mediaUidMap = weixinBindingService.getWeixinUidBindingByMobile(map);
            String mediaUid = "";
            if (null != mediaUidMap) {
                mediaUid = String.valueOf(mediaUidMap.get("MEDIA_UID"));
            } else {
                mediaUid = "";
            }

            if (null == mediaUid || "".equalsIgnoreCase(mediaUid) || "null".equalsIgnoreCase(mediaUid)) {
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                        Message.CnDescriptionExpression.WEIXIN_BYMOBILE_ERROR);
            } else {
                Map weixinMap = new HashMap<>();
                weixinMap.put("mediaUid", mediaUid);
                result = CommonUtil.setResultStringCn(weixinMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[通过手机号查询用户绑定微信号]输入手机号为：" + phoneNum + "###mediaUid获取异常");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.WEIXIN_BYMOBILE_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 获取有效分享签名
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getAllToken", method = RequestMethod.GET)
    public void getAllToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getAllToken方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        try {
            Map<String, Object> signaTureMap = weixinBindingService.getAllToken();
            if (null == signaTureMap) {
                signaTureMap = new HashMap<>();
            }
            result = CommonUtil.setResultStringCn(signaTureMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[获取AllToken签名]AllToken获取失败");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE, "",
                    Message.CnDescriptionExpression.ALLACCESSTOKEN_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 添加微信全局token（用于模板消息）
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/insertAllToken")
    public void insertAllToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice insertAllToken方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String accessToken = paramsMap.get("accessToken");
        String createPer = "ordjfdivn789_fdjksovmk";

        // 设置参数
        AllAccessToken aat = new AllAccessToken();
        aat.setAccesstoken(accessToken);
        aat.setCreatePer(createPer);
        try {
            weixinBindingService.insertAllToken(aat);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加AllToken签名]AllToken获取失败");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.ADD_ACCESSTOKEN_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 修改全局token数据(用于模板信息)
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/updateAllToken")
    public void updateAllToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice updateAllToken方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String accessToken = paramsMap.get("accessToken");
        String createPer = "otXu5swhlifvm8B2u9DoGJc5yclo";

        logger.info("****javasevice********accessToken:" + accessToken + "&createPer=" + createPer);

        try {
            weixinBindingService.updateAllToken(paramsMap);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改全局token数据(用于模板信息)失败！当前微信标识为：" + createPer);
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.UPDATE_ACCESSTOKEN_ERROR);
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 根据userID查询绑定微信ID
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/queryMediaUid")
    public void queryMediaUid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice queryMediaUid方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String userId = paramsMap.get("userId");

        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);

        WeixinMediaBinding mediaBinding = new WeixinMediaBinding();
        mediaBinding.setUserId(Integer.parseInt(userId));// 用户Id
        try {
            String mediaUid = weixinBindingService.queryMediaUid(mediaBinding);
            if (null != mediaUid && !"".equalsIgnoreCase(mediaUid)) {

                Map resultMap = new HashMap<>();
                resultMap.put("mediaUid", mediaUid);
                result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            } else {
                logger.error("[该用户未绑定userId]：" + userId);
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                        Consts.SUCCESS_DESCRIBE, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CommonUtil.responseJson(result, response);
    }

    /**
     * 发送模板（充值，提现申请中，购买，加息券,代金券）消息
     *
     * @return
     */
    @RequestMapping(value = "/sendWeixinModelInfo")
    public void sendWeixinModelInfo(PrintWriter out, String current, HttpServletRequest request,
                                    HttpServletResponse res) {
        // 发送模板消息
        String resultInfo = WeixinRquestUtil.sendWeixinModelMessage(request, weixinBindingService);
        try {
            System.out.println("result---------------");
            int result = Integer.parseInt(resultInfo);
            System.out.println("result=========" + result);
            if (result == 0) {
                resultInfo = CommonUtil.setResultStringCn(new HashMap(), Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
                        "");
            } else {
                resultInfo = CommonUtil.setResultStringCn(new HashMap(), Consts.CHECK_CODE, "error", "");
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            resultInfo = CommonUtil.setResultStringCn(new HashMap(), Consts.CHECK_CODE, "error", "");
            e.printStackTrace();
        }

        CommonUtil.responseJson(resultInfo, res);
    }

    /**
     * app获取滚动公告信息system_setting
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getSystemSettingInfo")
    public void getSystemSeetingInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getSystemSettingInfo方法：");
        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        NoticeInfo noticeInfo = userService.getSystemSettingInfo(map);
        ResultDTO<NoticeInfo> resultDTO = null;
        if (noticeInfo == null) {
            logger.error("[查询APP、微信滚动公告信息]查无此数据");
            resultDTO = new ResultDTO<NoticeInfo>(ResultCode.SUCCESS, Message.CnDescriptionExpression.SYSTEMSETTING_NULL_ERROR);
        } else {
            resultDTO = new ResultDTO<NoticeInfo>(ResultCode.SUCCESS);
        }
        resultDTO.setRecord(noticeInfo);
        String resultJson = resultDTO.toJsonString();
        logger.info("result：" + resultJson);
        ResponseUtil.write(response, resultJson);
        logger.info("=========结束javaservice getSystemSettingInfo方法：");
        return;
    }

    /**
     * 密码检验
     *
     * @param request
     * @return response
     * @throws Exception
     * @throws IllegalArgumentException
     * @throws Exception
     */
    @RequestMapping(value = "/checkPassword")
    public void checkPassword(HttpServletRequest request, HttpServletResponse response)
            throws IllegalArgumentException, Exception {
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);

        try {
            // 数据检查
            Map<String, String> checkMap = checkPasswordCheck(paramsMap);
            if (null == checkMap || !Consts.SUCCESS_CODE.equals(checkMap.get("code"))) {
                String result = CommonUtil.setResultStringCn(new HashMap<>(), checkMap.get("code"), "",
                        checkMap.get("message"));
                // 处理返回结果
                CommonUtil.responseJson(result, response);
                return;
            }

            logger.debug("请求手机号：" + paramsMap.get("phoneNum") + "发送标识:" + paramsMap.get("setupFlag"));

            // 业务处理
            String result = "";
            String phoneNum = paramsMap.get("phoneNum");
            Map<String, Object> map = new HashMap<>();
            map.put("mobile", phoneNum);
            try {
                User user = userService.getUserByParm(map);
                if (user == null) {
                    Map<String, Object> errorMap = errorMessageService.getErrorMessage("USERORPASSWORD_IS_EXCEPTION");
                    String errMsg = getErrorMsg(errorMap);
                    logger.error(errMsg);
                    result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "", errMsg);
                } else {
                    result = userService.checkPassword(paramsMap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            logger.error("登录校验发生异常:" + e.getMessage());
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("BUSINESSE_ERROR");
            String errMsg = getErrorMsg(errorMap);
            String result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.ERROR_CODE, "", errMsg);
            CommonUtil.responseJson(result, response);
        }
    }

    /**
     * 校验密码数据检查
     *
     * @param paramsMap
     * @return
     * @throws Exception
     */
    private Map<String, String> checkPasswordCheck(Map<String, String> paramsMap) throws Exception {
        Map<String, String> resMap = new HashMap<String, String>();
        String phoneNum = paramsMap.get("phoneNum");
        String password = paramsMap.get("password");
        // 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String setupFlag = paramsMap.get("setupFlag");

        // 手机号码
        if (StringUtils.isBlank(phoneNum)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("MOBILE_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            resMap.put("code", Consts.CHECK_CODE);
            resMap.put("message", errMsg);
            return resMap;
        }

        // 密码
        if (StringUtils.isBlank(password)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000010");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            resMap.put("code", Consts.CHECK_CODE);
            resMap.put("message", errMsg);
            return resMap;
        }

        // 发送标识
        if (StrUtil.setupFlagCheck(setupFlag) == false) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000016");
            String errMsg = getErrorMsg(errorMap);
            logger.error("校验验证码数据检查失败：" + errMsg);
            resMap.put("code", Consts.CHECK_CODE);
            resMap.put("message", errMsg);
            return resMap;
        }

        resMap.put("code", Consts.SUCCESS_CODE);
        resMap.put("message", Consts.SUCCESS_DESCRIBE);
        return resMap;
    }

    /**
     * 登陆数据检查
     *
     * @param params
     * @return
     * @throws Exception
     */
    private ResultDTO loginPasswordCheck(JSONObject params) throws Exception {
        Map<String, String> resMap = new HashMap<String, String>();
        String userName = params.getString("userName");// 用户名
        String type = params.getString("type");// 登陆类型：手机或者邮箱
        String setupFlag = params.getString("setupFlag");// 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String password = params.getString("password");// 密码

        if (StringUtils.isBlank(userName)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("USER_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        if (StringUtils.isBlank(password)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("PASSWORD_IS_NULL");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        if (StringUtils.isBlank(type)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000015");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        if (!("mobile".equals(type) || "mail".equals(type))) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000015");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }

        // 发送标识
        if (!StrUtil.setupFlagCheck(setupFlag)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000016");
            String errMsg = getErrorMsg(errorMap);
            logger.error("登陆数据检查失败： " + errMsg);
            return new ResultDTO(ResultCode.FAILED, errMsg);
        }
        return new ResultDTO(ResultCode.SUCCESS);
    }

    /**
     * 注册
     *
     * @param request
     * @return response
     * @throws Exception
     */
    @RequestMapping(value = "/registerLoginPassword")
    public void registerLoginPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }

        JSONObject params = RequestUtil.decodeDataJson(request);
        logger.info("data：" + params);

        Map<String, Object> jsonMap = new HashMap<>();

        String userName = params.getString("userName");// 用户名-手机号
        String password = params.getString("password");// 登录密码
        String passwordConfirm = params.getString("passwordConfirm");// 确认密码

        // 170开头的手机号段暂不支持注册
        String condition = "";
        try {
            condition = activityService.findParamValueByName("register_forbidden_mobile");
            logger.info("查询系统参数表，获取限制注册手机号限制条件：" + condition);
        } catch (Exception e) {
            logger.error("获取禁止注册手机号参数异常", e);
        }
        if ((!"".equals(condition)) && (!CommonUtil.registerPhoneLimitCheck(userName, condition))) {
            logger.info("系统限制注册手机号：" + userName + "，限制条件：" + condition);
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000027");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
            return;
        }

        // 登录 密码不能为空
        if (null == password || "".equalsIgnoreCase(password)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000010");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
            return;
        }
        // 确认密码不能为空
        if (null == passwordConfirm || "".equalsIgnoreCase(passwordConfirm)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000011");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
            return;
        }
        // 两次密码输入不一致
        if (!passwordConfirm.equalsIgnoreCase(password)) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000012");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
            return;
        }

        Boolean checkPassword = Validator.isPassword(password);
        if (!checkPassword) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000013");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
            return;
        }

        String channel = params.getString("channel");// 渠道
        // 发送标识（是来自网站用户，还是手机用户）:1：为来自网站的；2：来自手机的
        String setupFlag = params.getString("setupFlag");
        String invitationCode = params.getString("invitationCode");// 邀请码
        // 微信ID
        String weixinId = params.getString("weixinId");

        String ip = CommonUtil.getClientIP(request);

        IpLogBean logBean = new IpLogBean();
        logBean.setIp(ip);
        logBean.setAction("注册");
        logBean.setStatus(Consts.ERROR_CN);
        if ("2".equals(setupFlag)) {
            logBean.setDetail(userName + "在APP端进行了注册操作");
        } else {
            logBean.setDetail(userName + "在WEB端进行了注册操作");
        }
        try {

            if (StringUtils.isBlank(channel)) {
                params.put("channel", "OTHERS");
                channel = "OTHERS";
            }

            // 创建用户
            User user = new User();
            String passwordMd5 = "";
            if (StringUtils.isNotBlank(password)) {
                passwordMd5 = MD5.md5(password);
            }

            user.setMobile(userName);
            // 设置登录密码
            user.setPassword(passwordMd5);

            user.setChannel(channel);
            user.setLastest_login_ip(ip);
            String token = "register" + "_" + CommonUtil.getUuid();
            user.setLogin_token(token);
            if ("2".equals(setupFlag)) {
                user.setUtm_source_type("MOBILE");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
            } else {
                user.setUtm_source_type("CHANNEL");// 用户来源类型（CHANNEL:渠道-线上;AGENCY:机构-线下;AT_SYSTEM:爱特系统用户;AGENCY_SYSTEM:机构系统用户;）
            }

            // 注册邀请码
            if (StringUtils.isNotBlank(invitationCode)) {
                user.setInviterInvitationCode(invitationCode.toUpperCase());
            }
            user.setWeixin_id(weixinId == null ? "" : weixinId);

            // 添加用户(T_TUSER表和USER_INFO表)
            this.userService.addUsers(user);

            // 注册成功
            jsonMap.put("userId", user.getId());
            jsonMap.put("userName", userName);
            jsonMap.put("identityName", "");
            jsonMap.put("idCard", "");
            jsonMap.put("ftpPathOriginal", "");
            jsonMap.put("ftpPathDispose", "");
            jsonMap.put("emailValidate", user.getEmail_validate());
            jsonMap.put("idcardValidate", "N");
            jsonMap.put("mobileValidate", user.getMobile_validate());
            jsonMap.put("email", "");
            jsonMap.put("mobile", user.getMobile());
            jsonMap.put("bankCardValidate", "N");
            jsonMap.put("weixinId", user.getWeixin_id());
            jsonMap.put("uuid", user.getLogin_token());

            logBean.setStatus(Consts.SUCCESS_CN);
            if (StringUtils.isNotBlank(ip)) {
                logBean.setUser(user.getId() + "");
                IpLog.printIpLog(logBean);
            }

            // 按渠道统一发放福利
            try {
                Map<String, Object> welfareParams = new HashMap<>();
                welfareParams.put("userId", user.getId());
                welfareParams.put("channelId", user.getUtm_source());
                welfareParams.put("mobile", user.getMobile());
                welfareParams.put("channelEnName", channel);
                channelWelfareParametersService.addWelfareBychannelEnName(welfareParams, request);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("注册赠送福利异常:" + e.getMessage());
            }

            // 注册送积分
            if (null != user.getId() && !StringUtil.isEmpty(user.getMobile())) {
                logger.info("#### 开始执行--->注册送积分 #####");
                pointService.registerPoint(user);
                logger.info("#### 执行完成--->注册送积分 #####");
            } else {
                logger.info("#### 注册送积分时，用户信息有误，userId=" + user.getId() + ",mobile=" + user.getMobile() + " ####");
            }

            // 处理返回结果
            ResultDTO result = new ResultDTO(ResultCode.SUCCESS);
            result.setRecord(jsonMap);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            logger.error("注册异常:" + e.getMessage());
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("BUSINESSE_ERROR");
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED,
                    getErrorMsg(errorMap)));
        }
    }

    /**
     * 查询任务列表
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getTaskList")
    public void getTaskList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getTaskList方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String userId = paramsMap.get("userId");
        if (null == userId || "".equalsIgnoreCase(userId)) {
            logger.error("[查询任务列表]用户Id为空");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.EM000000002);
            CommonUtil.responseJson(result, response);
            return;
        }

        try {
            JSONArray taskinfoList = userService.getTaskList(userId);
            if (taskinfoList == null) {
                logger.error("[查询任务列表]查无此数据");
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                        Message.CnDescriptionExpression.TASK_LIST_NULL_ERROR);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("list", taskinfoList);
                result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            }
            // 处理返回结果
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            logger.error("[查询任务列表]异常:" + e.getMessage());
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.ERROR_CODE, "",
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            // 处理返回结果
            CommonUtil.responseJson(result, response);
        }

    }

    /**
     * 查询总菜单功能定制表数据
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getAllIcoFuncList")
    public void getAllIcoFuncList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getAllIcoFuncList方法：");
        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }
        ResultDTO result;
        // 解密请求参数-
//		Map<String, String> paramsMap = RequestUtil.decodeDataToString(request);
//		String userId = "";
//		userId = paramsMap.get("userId");
        String viewFlag = "2";//微信为1，app为2
//		logger.info("=========传入的参数：" + paramsMap.toString());
        List<IcoUserFuncInfo> IcoUserFuncList;
        // 默认快捷菜单(新版本)
        IcoUserFuncList = userService.getAllIcoFuncList(viewFlag);
        if (IcoUserFuncList == null) {
            logger.error("[查询总菜单功能定制表数据]查无此数据");
            result = new ResultDTO<>(ResultCode.FAILED, "[查询总菜单功能定制表数据]查无此数据");
        } else {
            Map<String, Object> resultMap = new HashMap<>();
            String webPath = systemSettingService.getSystemSettingValueByName("spring_festival_topicon_path");
            String backIcon = "";
            String springBack = "";

//			更多快捷菜单
//			IcoUserFuncInfo icoUserFuncInfo = userService.getIcoFuncGd();
//			IcoUserFuncList.add(7, icoUserFuncInfo);
            // 节日图标开关
            String newYearFlag = systemSettingService.getSystemSettingValueByName("cjtbkg");
            if ("1".equals(newYearFlag)) {
                springBack = systemSettingService.getSystemSettingValueByName("spring_festival_back_icon");
                backIcon = webPath + springBack;
                String newYearIcon = systemSettingService
                        .getSystemSettingValueByName("spring_festival_top_icon");
                if (StringUtil.isNotEmpty(newYearIcon) && StringUtil.isNotEmpty(webPath)) {
                    String[] newYearIconArr = newYearIcon.split("\\|");
                    for (int i = 0; i < newYearIconArr.length; i++) {
                        IcoUserFuncList.get(i).setImage_url_choose(webPath + newYearIconArr[i]);
                    }
                }
            }
            result = new ResultDTO<>(ResultCode.SUCCESS);
            result.setRecords(IcoUserFuncList);
            resultMap.put("backIcon", backIcon);
            result.setRecord(resultMap);
        }
        // 处理返回结果
        ResponseUtil.write(response, result);
    }

    /**
     * 发布个人菜单定制表
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/addUserIcoFuncList")
    public void addUserIcoFuncList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice addUserIcoFuncList方法：");
        String result = "";
        // 解密请求参数-
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String userId = paramsMap.get("userId");
        String icoFuncId = paramsMap.get("icoFuncId") == null ? "" : paramsMap.get("icoFuncId");// 菜单定制ID
        String viewFlag = paramsMap.get("viewFlag") == null ? "2" : "1";
        String flag = paramsMap.get("flag") == null ? "" : paramsMap.get("flag");
        if (null == userId || "".equalsIgnoreCase(userId)) {
            logger.error("[发布个人菜单定制表]用户Id为空");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.EM000000002);
            CommonUtil.responseJson(result, response);
            return;
        }
        userId = userId.trim();
        // if(null==icoFuncId || "".equalsIgnoreCase(icoFuncId)){
        // logger.error("[发布个人菜单定制表]菜单定制ID为空");
        // result = CommonUtil.setResultStringCn(new HashMap<String,Object>(),
        // Consts.CHECK_CODE,
        // "",Message.CnDescriptionExpression.BUSINESSE_ERROR);
        // CommonUtil.responseJson(result, response);
        // return;
        // }

        String[] icoFuncIdData = icoFuncId.split(",");

        if (null == icoFuncIdData) {
            logger.error("[发布个人菜单定制表]菜单定制ID为空");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            CommonUtil.responseJson(result, response);
            return;
        }
        int chooseNum = 4;
        if ("1".equals(flag)) {
            chooseNum = 7;
        }
        // 可定制个菜单
        if (icoFuncIdData.length > chooseNum) {
            logger.error("[发布个人菜单定制表]菜单定制数量不能大于" + chooseNum + "个");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    "[发布个人菜单定制表]菜单定制数量不能大于" + chooseNum + "个");
            CommonUtil.responseJson(result, response);
            return;
        }

        List<IcoUserFuncInfo> IcoUserFuncList = userService.getAllIcoFuncList(viewFlag);
        int icoFuncount = 0;
        // 判断定制菜单id串是否存在
        if (IcoUserFuncList != null && !"".equals(icoFuncId)) {
            for (int i = 0; i < icoFuncIdData.length; i++) {
                for (IcoUserFuncInfo icoUserFuncInfo : IcoUserFuncList) {
                    if (Integer.valueOf(icoFuncIdData[i]) == icoUserFuncInfo.getId()) {
                        icoFuncount++;
                    }
                }
            }
        }

        if (icoFuncount > chooseNum) {
            logger.error("[发布个人菜单定制表]菜单定制数量不能大于" + chooseNum + "个");
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    "[发布个人菜单定制表]菜单定制数量不能大于" + chooseNum + "个");
            CommonUtil.responseJson(result, response);
            return;
        }
        // 如果用户已经定制过菜单，删除重新定制菜单
        List<IcoUserFuncInfo> usericoFunlist = userService.getUserIcoFuncList(userId);
        if (usericoFunlist != null) {
            userService.deleteUserIcoFuncSort(userId);
        }
        try {
            if (!"".equals(icoFuncId)) {
                // 定制用户菜单
                for (int i = icoFuncIdData.length - 1; i >= 0; i--) {
                    Map<String, String> requestInfoMap = new HashMap<String, String>();
                    requestInfoMap.put("userId", userId);
                    requestInfoMap.put("icoFuncId", icoFuncIdData[i]);
                    userService.addUserIcoFuncList(requestInfoMap);
                }
            }
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.SUCCESS_CODE,
                    Consts.SUCCESS_DESCRIBE, "");
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            logger.error("[发布个人菜单定制表]异常:" + e.getMessage());
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            CommonUtil.responseJson(result, response);
        }
    }

    /**
     * 查询用户userid
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/getUserIdByMobile")
    public void getUserIdByMobile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice getUserIdByMobile方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String phoneNum = paramsMap.get("mobile");
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", phoneNum);
        try {
            User user = userService.getUserByParm(map);
            if (user == null) {
                logger.error("手机号码未注册！");
                result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                        Message.CnDescriptionExpression.MOBILE_NOT_EXIST);
            } else {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("userId", user.getId());
                result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
            }
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            // e.printStackTrace();
            logger.error("[查询用户id]异常:" + e.getMessage());
            result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.CHECK_CODE, "",
                    Message.CnDescriptionExpression.BUSINESSE_ERROR);
            CommonUtil.responseJson(result, response);
        }

    }

    /**
     * 查询是否完成任务
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/isCompleteTask")
    public void isCompleteTask(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("=========进入javaservice isCompleteTask方法：");
        String result = "";
        // 解密请求参数
        Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
        logger.info("=========传入的参数：" + paramsMap.toString());

        String userId = paramsMap.get("userId");
        BigDecimal adjustRate = BigDecimal.ZERO; // 获取活期利率
        BigDecimal signInRateRises = BigDecimal.ZERO; // 获取签到加息
        BigDecimal couponsRateRises = BigDecimal.ZERO; // 获取当日加息利率
        BigDecimal totalRate = BigDecimal.ZERO; // 总加息
        // 查询用户最高收益值上限
        float userMaxRaise = Float.valueOf(rateRisesCouponsService.findParamValueByName("user_max_raise"));
        // 获取加息券加息(簽到加息+加息券加息)
        Map<String, String> paramsMapStr = CommonUtil.decryptParamters(request);
        paramsMapStr.put("finaceId", "1");
        paramsMapStr.put("userId", userId);
        String resultStr = depositService.queryMoneyFundDetail(paramsMapStr);
        Map<String, Object> resultMapAll = null;
        if (null != resultStr && !"".equals(resultStr)) {
            resultMapAll = CommonUtil.jsonObjToHashMap(resultStr);
        }

        if (resultMapAll != null) {
            // 获取活期利率
            adjustRate = new BigDecimal(resultMapAll.get("adjustRate").toString());
            // 获取签到加息
            signInRateRises = new BigDecimal(resultMapAll.get("signInRateRises").toString());
            // 获取当日加息利率
            couponsRateRises = new BigDecimal(resultMapAll.get("couponsRateRises").toString());
            // 总加息
            totalRate = signInRateRises.add(couponsRateRises).add(adjustRate);
        }

        if (totalRate.floatValue() >= userMaxRaise) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isCompleteTask", "1");
            result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
        } else {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("isCompleteTask", "0");
            result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE, "");
        }
        CommonUtil.responseJson(result, response);

    }

    /**
     * 获取验证码
     *
     * @param request
     * @return response
     * @throws Exception
     */
    @RequestMapping(value = "/captchaByKcode")
    public void captchaByKcode(HttpServletRequest request, HttpServletResponse response) {
        logger.info("=========进入javaservice captchaByKcode方法：");
        // 解密请求参数

        try {
            JSONObject paramsMap = RequestUtil.decodeDataJson(request);
            // 数据检查
            // 数据检查
            ResultDTO<String> checkDto = getCaptchaCheck(paramsMap);
            if (null == checkDto || checkDto.codeEq(ResultCode.FAILED)) {
                ResponseUtil.write(response, checkDto);
                return;
            }
            logger.info("=========传入的参数(userMobile)：" + checkDto.getRecord());
            // 手机k码流程
            Map<String, Object> mobileKcodeMsgMap = kcodeChannelService.mobileKCode("验证联通手机号", checkDto.getRecord(),
                    "2");
            if (mobileKcodeMsgMap != null) {
                String checkMobileResult = CommonUtil.setResultStringCn(mobileKcodeMsgMap, Consts.CHECK_CODE, "",
                        getErrorMsg(mobileKcodeMsgMap));
                // 处理返回结果
                CommonUtil.responseJson(checkMobileResult, response);
                return;
            }

            // // 判断联通手机号码是否激活过k码
            // Map<String, Object> unionParamMap=new HashMap<>();
            // unionParamMap.put("unionMobile",paramsMap.get("phoneNum"));
            // List<UserLDActivityInfo>
            // activityInfoByUnionMobileList=activityService.findActivityInfoByParm(unionParamMap);//通过联通手机号码激活信息
            //
            // if(null!=activityInfoByUnionMobileList &&
            // activityInfoByUnionMobileList.size() > 0){
            // //提示信息修改
            // Map<String, Object>
            // errorMap=errorMessageService.getErrorMessage("EM000000023");
            // String result = CommonUtil.setResultStringCn(
            // errorMap, Consts.CHECK_CODE, "",
            // getErrorMsg(errorMap));
            // // 处理返回结果
            // CommonUtil.responseJson(result, response);
            // return;
            // }

            // 业务处理
            paramsMap.put("userMobile", checkDto.getRecord());
            // 查询短信发送每日限额次数
            String infoTime = this.userService.getSystemSettingValue("day_captcha_time");
            if (null == infoTime || "".equalsIgnoreCase(infoTime)) {
                infoTime = "5";
            }
            // 查询是否限制短信发送
            ResultDTO result = userService.getCaptcha(paramsMap, infoTime);
            logger.info("=========获取验证码result：" + result.toJsonString());
            CommonUtil.responseJson(result, response);
        } catch (Exception e) {
            logger.error("获取验证码发生异常:" + e.getMessage());
            String result = CommonUtil.setResultStringCn(new HashMap<>(), Consts.ERROR_CODE, "",
                    Message.CnDescriptionExpression.GET_CAPTCHA_FAILED);
            CommonUtil.responseJson(result, response);
        }
    }

    @RequestMapping(value = "/checkMoblieAll")
    public void checkMoblieAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("==========激活k码校验 checkMoblieAll start");

        if (!RequestUtil.validSign(request)) {
            logger.info("无效签名");
            ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
            return;
        }


        // 验证校验码
        // 解密请求参数
        JSONObject params = RequestUtil.decodeDataJson(request);
        logger.info("data：" + params);

        try {
            // 数据检查
            ResultDTO checkResult = checkCaptchaCheck(params);
            if (null == checkResult || checkResult.codeEq(ResultCode.FAILED)) {
                ResponseUtil.write(response, checkResult);
                return;
            }
            logger.info("请求手机号：" + params.getString("phoneNum") + "请求验证码：" + params.getString("checkCode") + "发送标识:"
                    + params.getString("setupFlag"));

            // 业务处理
            ResultDTO result = userService.checkCaptcha(params);
            // 验证码校验失败
            if (null == result || result.codeEq(ResultCode.FAILED)) {
                ResponseUtil.write(response, result);
                return;
            }
        } catch (Exception e) {
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("GET_CAPTCHA_FAILED");
            String errMsg = getErrorMsg(errorMap);
            logger.error("获取验证码发生异常:" + e.getMessage());
            ResponseUtil.write(response, new ResultDTO(ResultCode.FAILED, errMsg));
            return;
        }

        try {
            // 用户手机号
            String phoneNum = nullToBlank(params.getString("phoneNum"));
            logger.info("==========激活k码校验 checkMoblieAll 参数phoneNum:" + phoneNum);
            // 手机k码流程
            Map<String, Object> mobileKcodeMsgMap = kcodeChannelService.mobileKCode("验证联通手机号", phoneNum, "2");
            if (mobileKcodeMsgMap != null) {
                String result = CommonUtil.setResultStringCn(mobileKcodeMsgMap, Consts.CHECK_CODE, "",
                        getErrorMsg(mobileKcodeMsgMap));
                // 处理返回结果
                CommonUtil.responseJson(result, response);
                return;
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            logger.info("==========激活k码校验 checkMoblieAll 异常：" + e.getMessage());
            Map<String, Object> errorMap = errorMessageService.getErrorMessage("EM000000021");

            String result = CommonUtil.setResultStringCn(errorMap, Consts.ERROR_CODE, "", getErrorMsg(errorMap));
            // 处理返回结果
            CommonUtil.responseJson(result, response);
            return;
        }

        logger.info("==========激活k码校验 checkMoblieAll end");
        // 处理返回结果
        String result = CommonUtil.setResultStringCn(new HashMap(), Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE,
                Consts.SUCCESS_DESCRIBE);
        CommonUtil.responseJson(result, response);
        return;
    }

    /**
     * 提示信息接口
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/promptInfo")
    public void promptInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {

        try {

            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);
            JSONObject params = RequestUtil.decodeDataJson(request);

            ResultDTO result = userService.promptInfo(params, header);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            logger.error("注册手机号校验接口失败：" + e.getMessage());
            ResponseUtil.write(response, ResultConstant.FAILED);
        }
    }

    /**
     * @param @param  errorMap
     * @param @return
     * @return String
     * @throws @author wuhan
     * @Description: 获取错误信息
     * @date 2016-7-13
     */
    private String getErrorMsg(Map<String, Object> errorMap) {
        // TODO Auto-generated method stub
        ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
        String emsStr = "";
        if (null != emsEntity) {
            emsStr = emsEntity.getMessage_content();
        }
        return emsStr;
    }

    private String nullToBlank(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    /**
     * 提示信息接口
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/findUser")
    public void findUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);

            User user = userService.getUserDetail(header.userId2String());
            if (null == user) {
                ResponseUtil.write(response, ResultConstant.SUCCESS);
                return;
            }

            JSONObject userJson = new JSONObject();
            userJson.put("enable", user.getEnable());
            userJson.put("mobile", user.getMobile());
            userJson.put("mobile_validate", user.getMobile_validate());
            userJson.put("nick_name", user.getNick_name());
            userJson.put("reg_time", null == user.getReg_time() ? null :
                    DateUtil.toDateTimeString(user.getReg_time()));
            userJson.put("userinfo_finished", user.getUserinfo_finished());
            userJson.put("user_type", user.getUser_type());
            userJson.put("idcard_validate", user.getIdcard_validate());
            userJson.put("llpay_idcard_vaildate", user.getLlpay_idcard_vaildate());
            userJson.put("password_cash", null == user.getPassword_cash() ? "" :
                    DigestUtils.md5Hex(user.getPassword_cash()));

            // 是否绑卡
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("userId", header.userId2String());
            Map<String, Object> userCardMap = this.userCardService.queryUserCardInfoByUserId(requestMap);
            if (Integer.parseInt(userCardMap.get("userCardInfoCount").toString()) != 0) {
                userJson.put("isBindingCard", "Y");
            } else {
                userJson.put("isBindingCard", "N");
            }

            ResultDTO<JSONObject> result = new ResultDTO<>(ResultCode.SUCCESS);
            result.setRecord(userJson);
            ResponseUtil.write(response, result);
        } catch (Exception e) {
            logger.error("注册手机号校验接口失败：", e);
            ResponseUtil.write(response, ResultConstant.FAILED);
        }
    }

    @RequestMapping(value = "/validPasswd")
    public void validPasswd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {

            if (!RequestUtil.validSign(request)) {
                logger.info("无效签名");
                ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
                return;
            }
            if (!RequestUtil.validToken(request)) {
                logger.info("无效token");
                ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
                return;
            }
            RequestHeader header = RequestUtil.decodeHeader(request);

            JSONObject params = RequestUtil.decodeDataJson(request);
            if (null == params) {
                logger.info("参数列表为空");
                ResponseUtil.write(response, ResultConstant.FAILED);
                return;
            }
            ResponseUtil.write(response, this.userService.validPasswd(params, header));
        } catch (Exception e) {
            logger.error("注册手机号校验接口失败：", e);
            ResponseUtil.write(response, ResultConstant.FAILED);
        }
    }
}
